//
//  TRHomeViewController.m
//  TLBS
//
//  Created by tarena on 14-3-28.
//  Copyright (c) 2014年 tarena. All rights reserved.
//
#import "WeiboPaser.h"
#import "MapViewController.h"
#import "TRHomeViewController.h"
#import "WeiboCell.h"
#import <MapKit/MapKit.h>
#import "TRAppDelegate.h"
#import "TRBaiduMapUtils.h"
#import "TRMyRequest.h"
#import "Weibo.h"
#import "SBJSON.h"
#import "TRXMPPManager.h"
@interface TRHomeViewController ()

@property (nonatomic, weak)TRAppDelegate *app;
@property (nonatomic, strong)NSMutableArray *requests;
@property (nonatomic, strong)NSMutableArray *weibos;
@end

@implementation TRHomeViewController



- (void)viewDidLoad
{
    self.requests = [NSMutableArray array];
    self.app = [UIApplication sharedApplication].delegate;
    [super viewDidLoad];
    [self initBarUI];
    [self loadWeibo];
}

-(void)loadWeibo{
    self.weibos = [NSMutableArray array];

 //设置一个默认的经纬度
    CLLocationCoordinate2D location;
    location.latitude =39.90960;
    location.longitude =116.397;

    [TRBaiduMapUtils serchPoiByLocation:[NSString stringWithFormat:@"%f,%f",location.longitude,location.latitude] callback:^(NSArray *weiboIDs) {
        
        
        NSLog(@"id count = %d",weiboIDs.count);
        NSString *weiboIDsString = [weiboIDs componentsJoinedByString:@","];
        //通过得到的微博id列表获取所有的微博信息
        
        
        TRMyRequest *request = [[TRMyRequest alloc]init];
        [self.requests addObject:request];
        NSMutableDictionary *params = [NSMutableDictionary dictionary];
        [params setObject:weiboIDsString forKey:@"ids"];
        [request requestWithParams:params apiName:@"t/list" httpMethod:@"GET":^(NSString *jsonString) {
            NSDictionary *dic = [[jsonString JSONValue] objectForKey:@"data"];
            //如果一条数据都没有
            if ([dic isMemberOfClass:[NSNull class]]) {
                [self.tableView reloadData];
                return ;
            }
            
            NSArray *weibos = [dic objectForKey:@"info"];
           
            for (NSDictionary *weiboDic in weibos) {
                
                Weibo *w = [WeiboPaser paseWeiboByDictionary:weiboDic];
                [self.weibos addObject:w];
            }
            [self.tableView reloadData];
            [self.requests removeObject:request];
        }];
    }];

}
-(void)viewDidAppear:(BOOL)animated{
    
    dispatch_async(dispatch_get_main_queue(), ^{
        [self.app.weiboApi loginWithDelegate:self andRootController:self];
    });
}

-(void)initBarUI{
    self.navigationController.navigationBar.titleTextAttributes = @{NSForegroundColorAttributeName: [UIColor whiteColor]};
    UIBarButtonItem *refreshItem = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemRefresh target:self action:@selector(refreshAction)];
    [refreshItem setTintColor:[UIColor whiteColor]];
    
    self.navigationItem.leftBarButtonItems = @[self.navigationItem.leftBarButtonItem,refreshItem];
    
    
 
    
}
-(void)refreshAction{
    [self loadWeibo];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
#pragma mark - weibo
- (void)DidAuthFinished:(WeiboApiObject *)wbobj
{
    NSLog(@"%@   %@",wbobj.userName,wbobj.openid);
    
    //获取name
    NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
    NSString *userName = [ud objectForKey:@"userName"];
    if ( userName) {
        //初始化xmpp
        [[TRXMPPManager shareManager]connectWithOpendid:wbobj.openid andName:userName];

    }else{
        //发起请求活的userName;
        
        //从网络获取用户信息
        NSMutableDictionary *params = [NSMutableDictionary dictionaryWithObject:@"json" forKey:@"format"];
        [self.app.weiboApi requestWithParams:params  apiName:@"user/info" httpMethod:@"GET" delegate:self];
        

        
    }
       NSLog(@"授权成功！！");
}

-(void)didReceiveRawData:(NSData *)data reqNo:(int)reqno{
    
    NSString *resultString = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
    
   UserInfo *userInfo = [WeiboPaser paseUserInfoByJsonString:resultString];

      [[TRXMPPManager shareManager]connectWithOpendid:userInfo.openid andName:userInfo.name];
    
    NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
    [ud setObject:userInfo.name forKey:@"userName"];
    [ud synchronize];

    
}


#pragma mark - Table view data source
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
       NSLog(@"weibo count = %d",self.weibos.count);
    return self.weibos.count;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    Weibo *w = self.weibos[indexPath.row];
    return [w getHeight] + 70;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    WeiboCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
    Weibo *weibo = [self.weibos objectAtIndex:indexPath.row];
    cell.weibo = weibo;
    cell.delegate = self;
    return cell;
}

-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{
    if ([segue.identifier isEqualToString:@"map"]) {
        MapViewController *vc = segue.destinationViewController;
        vc.weibos = self.weibos;
    }
   
}
@end
